package com.net {

import laya.events.Event;
import laya.events.EventDispatcher;
import laya.net.Socket;
import laya.renders.Render;

public class GameSocket extends EventDispatcher {

	private var MAX_CONNECT_TIME:int = 10;
	private var DELAY:int = 15000;
	public var alive:Boolean = true;
	private var socket:*;
	private var options:Object;
	private var auth:Boolean;

	public function GameSocket(options:Object) {
		this.options = options;
		createConnect();
	}

	public function createConnect():void {
		if (MAX_CONNECT_TIME <= 0) {
			return;
		}
		connect();
	}

	private function connect():void {
		if (Render.isConchApp) {
			socket = Laya.PlatformClass.createClass("com.casino.gamemania.GameSocket").newObject();
			socket.call("connect", options.url);
		} else {
			socket = new Socket();
			socket.disableInput = true;
			this.auth = false;
			socket.on(Event.OPEN, this, openHandler);
			socket.on(Event.ERROR, this, errorHandler);
			socket.on(Event.MESSAGE, this, messageHandler);
			socket.on(Event.CLOSE, this, closeHandler);
			socket.connectByUrl(options.url);
		}
	}

	public function closeHandler(msg:*=null):void {
		if (!(msg is String)) {
			msg = msg.data;
		}
		console.log("GameSocket.closeHandler()", msg);
		Laya.timer.clear(this, heartbeat);
		Laya.timer.once(DELAY, this, reConnect);
	}

	public function messageHandler(evt):void {
//		AppManager.log(evt);
		try {
			if (!(evt is String)) {
				evt = evt.data;
			}
			var receives:Object = JSON.parse(evt);
			for(var i:int=0; i < receives.length; i++) {
				var data:Object = receives[i];
				if (data.op == 8) {
					auth = true;
					heartbeat();
					Laya.timer.loop(4 * 60 * 1000, this, heartbeat);
				}
				if (!auth) {
					Laya.timer.once(DELAY, this, getAuth);
				}
				if (auth && data.op == 5) {
					var notify:Function = this.options.notify;
					if(notify) notify(data.body);
				}
			}
		} catch (e:*) {
			console.log("error socket data", e+' *** '+evt);
		}

	}

	public function errorHandler(e):void {
		if (!(e is String)) {
			e = e.data;
		}
		console.log("GameSocket.errorHandler()", e);
		Laya.timer.clear(this, heartbeat);
		Laya.timer.once(DELAY, this, reConnect);
	}

	public function openHandler():void {
		console.log("GameSocket.openHandler()");
		getAuth();
		this.event(Event.OPEN);
	}

	private function reConnect():void {
		--MAX_CONNECT_TIME;
		DELAY *= 2;
		if(this.alive) this.createConnect();
	}

	private function heartbeat():void {
		send({
			'ver': 1,
			'op': 2,
			'seq': 2,
			'body': {}
		});
	}

	private function getAuth():void {
		send({
			'ver': 1,
			'op': 7,
			'seq': 1,
			'body': options.auth
		});
	}

	public function send(data:Object):void {
		if (Render.isConchApp) {
			socket.call("send", JSON.stringify(data));
		} else {
			socket.send(JSON.stringify(data));
		}
	}

	public function close():void {
		MAX_CONNECT_TIME = 0;
		if (Render.isConchApp) {
			socket.call("close");
		} else {
			socket.close();
		}
	}

}
}
